<template>
    <div>
        <Table :columns="columns" :paginatedData="paginatedData" :btnList="btnList" :btnListTable="btnListTable"
            :isFixedColumn="true" :columnWidth="200" :isMore="false" :isEndColumns="false"
            :footerBtnList="footerBtnList" :EndColumnsData="EndColumnsData" :tableLoading="loading" :total="total"
            @pageSize="handlePageSize" @currentPage="handleCurrentPage" @upImg="upImg" @handle-order="setOrder">
            <!-- 条件组,插槽 -->
            <template #default>
                <el-form :inline="true" :model="formBtnList" class="demo-form-inline">
                    <el-form-item label="">
                        <el-select v-model="formBtnList.lang" placeholder="请选择语言" style="width: 240px"
                            @change="handInquireYY">
                            <el-option v-for="item in languageOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="">
                        <el-select v-model="formBtnList.product_key" clearable filterable placeholder="产品"
                            style="width: 240px" @change="handKey">
                            <el-option v-for="item in aOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="">
                        <el-input v-model="formBtnList.search" :prefix-icon="Search" placeholder="请输入款式ID或款式名称" />
                    </el-form-item>
                </el-form>
            </template>
        </Table>

        <!-- 弹窗 -->
        <DialogCom ref="dialogCom" :dialogVisible="dialogVisible" :btnLoading="btnLoading" :tableTitle="tableTitle"
            :formData="formData" :ruleForm="ruleForm" :rules="rules" @beforeClose="beforeClose"
            @dialogSwitch="dialogSwitch" @submitForm="submitForm" />

        <commodityMentDialog ref="dialogCom" :dialogVisible="dialogVisible2" :btnLoading="btnLoading2"
            :ruleForm="ruleForm" :tableTitle="tableTitle2" :productKey="formBtnList.product_key"
            :titleIDText="titleIDText" @beforeClose="beforeClose" @submitForm="submitForm">
        </commodityMentDialog>
    </div>
</template>

<script setup lang='ts' name="commodityMent">
import { ref, reactive, onMounted } from 'vue'
import type { FormRules } from 'element-plus'
import Table from '@/components/Table.vue';
import DialogCom from '@/components/DialogCom.vue';
import commodityMentDialog from './commodityMentDialog.vue';
import { Search } from '@element-plus/icons-vue'
import { productStyle, productStyleDel, productStyleAdd, productStyleEdit, productStyleDetail, products, productStyleStatus,productStyleOrder } from '@/api/seriesMent/index.ts'
import { useRouteStore } from '@/stores/modules/counter.ts'
const routeStore = useRouteStore();
// 表格相关 开始
const loading = ref(false)
const btnLoading2 = ref(false)
const tableTitle2 = ref('');
const titleIDText = ref('');
// const product_key = ref('');
// 表头数据
const columns = ref([
    { prop: 'product_style_key', label: '款式key', width: 210 },
    { prop: 'style_name', label: '款式名称', width: 210 },
    // { prop: 'product_key', label: '产品ID', width: 180 },
    { prop: 'admin_name', label: '添加人', width: 210 },
    { prop: 'updated_time', label: '修改时间', width: '' },
    { prop: 'style_avatar_url', label: '款式预览图', width: 150, uploadAvatar: true },
    { prop: 'order', label: '权重排序', width: 120,order:true },
    { prop: 'status', label: '上架状态', width: 130, formatter: (row: any) => row.status == '1' ? '已上架' : '已下架' },
]);
// 固定最右侧列
const EndColumnsData = ref({ prop: 'status', label: '状态', width: 100, formatter: (row: any) => row.status == 'active' ? '上架中' : '已下架' })
// 表格数据
// 判断依据: judData
const paginatedData = ref([])
// 查询条件
const formBtnList = reactive({
    lang: routeStore.commodityMentLang ? routeStore.commodityMentLang : 'cn',
    // lang: '',
    search: '',
    product_key: '',
    page_size: 10,
    page: 1,
})
let aOptions = ref([])
// 获取产品选择框数据
const getProducts = () => {
    let para = {
        page: 1,
        page_size: 9999,
        lang: formBtnList.lang,
    }
    aOptions.value = []
    products(para).then((res: any) => {
        aOptions.value = res.data.products.map((item: any) => {
            return {
                value: item.product_key,
                label: item.product_name,
                id: item.product_id,
            }
        })
    })
}
let languageOptions = ref([
    {
        value: 'cn',
        label: '中文',
    },
    {
        value: 'en',
        label: '英文',
    },
])
let languageOptions2 = ref(languageOptions.value)
const handInquireYY = () => {
    routeStore.setCommodityMentLang(formBtnList.lang)
    // console.log(formBtnList.lang)
    getProducts()
    handInquire()
}
const handKey = (val: string) => {
    // const foundObject = aOptions.value.find(option => option.id === val)
    // if (val && foundObject.value) {
    //     formBtnList.product_key = foundObject.value
    // }
    handInquire()
}
const total = ref(0)
// 查询
const handInquire = () => {
    loading.value = true
    productStyle(formBtnList, 'cn').then((res: any) => {
        if (res.code === 200) {
            total.value = res.data.total
            if (res.data.total === 0) {
                paginatedData.value = []
                ElMessage.error(`款式信息不存在`)
                return
            }
            const processedData = res.data.product_styles.map((item: Object) => {
                return {
                    ...item,
                    judData: item.status  // 添加 judData 属性，并赋值为 status
                };
            });
            paginatedData.value = processedData
        } else {
            paginatedData.value = []
            ElMessage.error(`款式信息不存在`)
        }
    }).catch((error: any) => {
        paginatedData.value = []
        ElMessage.error(`请求错误: ${error}`)
    }).finally(() => {
        loading.value = false
    })
}
interface RuleForm {
    style_name: string
}
interface RuleFormItem {
    lang: string;
    style_name: string;
    status: string;
    product_key: string;
}
// 表单数据
const ruleForm = ref<RuleFormItem[]>([]);
// 重置表单方法
const resetForm = (initialData?: Partial<RuleForm>) => {
    ruleForm.value = [
        { lang: '中文', style_name: '', status: '1', product_key: '', },
        { lang: '英文', style_name: '', status: '1', product_key: '', }]
    if (initialData) {
        ruleForm.value = [
            { lang: '中文', style_name: '', status: '0', product_key: '', style_avatar_url: '' },
            { lang: '英文', style_name: '', status: '0', product_key: '', style_avatar_url: '' }]
        btnLoading2.value = true
        productStyleDetail(initialData.product_style_key).then((res: any) => {
            if (res.code === 200) {
                ruleForm.value = res.data.product_styles
                ruleForm.value.forEach(item => {
                    if (!('status' in item) || item.status === '') {
                        item.status = '0';
                    }
                });
                // console.log(111, ruleForm.value);
                if (ruleForm.value.length === 1 && res.data.product_styles[0].language === 'cn') {
                    ruleForm.value.push({ lang: 'en', style_name: '', status: '1' })
                } else if (ruleForm.value.length === 1 && res.data.product_styles[0].language === 'en') {
                    ruleForm.value.unshift({ lang: 'cn', style_name: '', status: '1' })
                }
                ruleForm.value[0].lang = '中文'
                ruleForm.value[1].lang = '英文'
                // console.log(22222, ruleForm.value);
            } else {
                ElMessage.error(`请求错误: ${res.msg}`)
            }
        }).finally(() => {
            btnLoading2.value = false
        })
    }
};
// 新增
const handAddAccount = () => {
    if (!formBtnList.product_key) return ElMessage.error('请选择产品')
    resetForm();
    tableTitle2.value = '新增款式'
    dialogVisible2.value = true
}
// 编辑
const handEditAccount = (row: object, index: number) => {
    titleIDText.value = row.product_style_key
    resetForm(row);
    tableTitle2.value = '编辑款式'
    dialogVisible2.value = true
}

const setOrder = (i: any, row: any)=>{
    ElMessageBox.prompt('请输入目标顺序（数字越大排序越靠后）', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    inputType: 'number', // 限制为数字输入
    inputPattern: /^[1-9]\d*$/, // 正整数校验（从1开始，避免0或负数）
    inputErrorMessage: '请输入有效的正整数（不能为空）',
  })
    .then(({ value }) => {
      // 二次校验：确保值不为空且为数字（兼容可能的类型转换问题）
      const orderNum = Number(value);
      if (!orderNum || isNaN(orderNum)) {
        ElMessage.error('排序值不能为空且必须为有效数字');
        return;
      }
      // 调用排序接口
      productStyleOrder({product_key:row.product_key,product_style_id:String(row.product_style_id),order:row.order,target_order:orderNum}).then((res) => {
        if(res.code === 200){
            ElMessage.success(`排序已更新为：${orderNum}`);
            // 刷新列表
            handInquire();
        }else{
            ElMessage.error(res.msg);
        }
      }).catch(() => {
        ElMessage.error('排序更新失败');
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消排序设置',
      });
    });
} 
// 上架
const listed = (row: object, index: number) => {
    console.log(row);
    if (!row.style_avatar_url) {
        ElMessage.error('请上传商品预览图再上架')
        return
    }
    ElMessageBox.confirm(
        '是否上架?',
        '上架',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
        }
    )
        .then(() => {
            let para = {
                product_style_id: row.product_style_id?.toString(),
                status: '1',
            }
            productStyleStatus(para).then((res: any) => {
                if (res.code === 200) {
                    ElMessage({
                        message: '成功',
                        type: 'success',
                    })
                } else {
                    ElMessage.error(`请求错误: ${res.msg}`)
                }
            }).catch((error: any) => {
                ElMessage.error(`请求错误: ${error.msg}`)
            }).finally(() => {
                handInquire()
            })
        })
        .catch(() => {

        })
}
// 下架
const removed = (row: object, index: number) => {
    ElMessageBox.confirm(
        '是否下架?',
        '下架',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
        }
    )
        .then(() => {
            let para = {
                product_style_id: row.product_style_id?.toString(),
                status: '0',
            }
            productStyleStatus(para).then((res: any) => {
                if (res.code === 200) {
                    ElMessage({
                        message: '成功',
                        type: 'success',
                    })
                } else {
                    ElMessage.error(`请求错误: ${res.msg}`)
                }
            }).catch((error: any) => {
                ElMessage.error(`请求错误: ${error.msg}`)
            }).finally(() => {
                handInquire()
            })
        })
        .catch(() => {

        })
}
// 重置
const handDerived = () => {
    // console.log('重置')
    formBtnList.lang = 'cn'
    formBtnList.search = ''
    formBtnList.product_key = ''
    getProducts()
    handInquire()
}
// 按钮组
const btnList = [
    { name: '查询', type: 'primary', click: handInquire, icon: '' },
    { name: '重置', type: 'success', click: handDerived, icon: '' },
]
const footerBtnList = [
    { name: '新增', type: 'primary', click: handAddAccount, icon: '' },
]
// 删除
const reject = (row: object, index: number) => {
    ElMessageBox.confirm(
        '确定删除此项吗？',
        '删除',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
        }
    ).then(() => {
        productStyleDel(row.product_style_key).then((res: any) => {
            if (res.code === 200) {
                ElMessage({
                    message: '成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(`请求错误: ${res.msg}`)
            }
        }).catch(() => {
        }).finally(() => {
            handInquire()
        })
    }).catch(() => {

    })
}
// 表单控件数据
let formData = reactive([
    { type: 'input', label: '款式名称', prop: 'style_name', span: 24, placeholder: '请输入' },
    { type: 'input', label: '款式描述', prop: 'style_desc', span: 24, placeholder: '请输入' },
    // { type: 'input', label: '名称', prop: 'style_name', span: 24, placeholder: '请输入' },
])
// 新增名称
const handAddName = (row: object, index: number) => {
    resetForm(row);
    tableTitle2.value = '新增名称'
    if (formBtnList.lang) {
        const targetValue = formBtnList.lang;
        const targetOption = languageOptions2.value.find(option => option.value === targetValue);
        if (targetOption) {
            languageOptions2.value.forEach(option => {
                option.disabled = false;
            });
            targetOption.disabled = true;
        }
    }
    formData = [
        { type: 'input', label: '名称', prop: 'name', span: 24, placeholder: '请输入' },
        { type: 'select', label: '语言', prop: 'lang', span: 24, placeholder: '请输入', options: languageOptions2.value },
    ]
    dialogVisible.value = true
}
// 操作列按钮组
const btnListTable = ref([
    { name: '上架', type: 'primary', click: listed, judgment: true, isShow: ['0'], },
    { name: '下架', type: 'warning', click: removed, judgment: true, isShow: ['1'], },
    { name: '编辑', type: 'success', click: handEditAccount },
    { name: '删除', type: 'danger', click: reject },
])
// 分页事件触发
const handlePageSize = (pageSize: number) => {// 每页大小
    // console.log('handlePageSize', pageSize);
    formBtnList.page_size = pageSize
    handInquire()
};
const handleCurrentPage = (currentPage: number) => {// 页码
    // console.log('handleCurrentPage', currentPage);
    formBtnList.page = currentPage
    handInquire()
};
// 行内上传图片
const upImg = (urlData: string, row: object) => {
    let para = {
        product_style_id: row.product_style_id,
        lang: formBtnList.lang,
        style_name: row.style_name,
        style_avatar_url: urlData,
        status: row.status,
    }
    productStyleEdit(para).then((res: any) => {
        if (res.code == 200) {
            ElMessage.success("修改成功")
        } else {
            ElMessage.error("修改失败")
        }
    })
}
// 表格相关 结束

// 弹窗相关
const dialogCom = ref<InstanceType<typeof DialogCom>>();
const btnLoading = ref(false)
// 表单校验配置
const rules = reactive<FormRules<RuleForm>>({
    style_name: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
    ],
})
// 弹窗 确认按钮
const submitForm = ((ruleFormData: any) => {
    if (tableTitle2.value === '新增款式') {
        btnLoading2.value = true
        productStyleAdd({ styles: ruleFormData }).then((res: any) => {
            if (res.code === 200) {
                if (dialogCom.value) {
                    dialogCom.value.cancelClick(); // 调用子组件方法
                }
                ElMessage({
                    message: '成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(`请求错误: ${res.msg}`)
                btnLoading2.value = false
            }
        }).catch((error: any) => {
            ElMessage.error(`请求错误: ${error.msg}`)
        }).finally(() => {
            btnLoading2.value = false
            handInquire()
        })
    } else if (tableTitle2.value === '编辑款式') {
        btnLoading2.value = true
        const simplifiedData = ref<SimplifiedRuleFormItem[]>(
            ruleFormData.map((item: any) => ({
                product_style_id: item.product_style_id?.toString(),
                lang: item.lang,
                style_name: item.style_name,
                style_avatar_url: item.style_avatar_url,
                status: item.status,
            }))
        )
        productStyleEdit({ styles: simplifiedData.value }).then((res: any) => {
            if (res.code === 200) {
                if (dialogCom.value) {
                    dialogCom.value.cancelClick(); // 调用子组件方法
                }
                ElMessage({
                    message: '成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(`请求错误: ${res.msg}`)
                btnLoading2.value = false
            }
        }).catch((error: any) => {
            ElMessage.error(`请求错误: ${error.msg}`)
        }).finally(() => {
            btnLoading2.value = false
            handInquire()
        })
    }
})
// 标题
const tableTitle = ref('');
const dialogVisible = ref(false);
const dialogVisible2 = ref(false);
const beforeClose = () => {
    titleIDText.value = ''
    dialogVisible.value = false;
    dialogVisible2.value = false;
}
const dialogSwitch = (row: object) => {
    console.log('row: ', row);

}

onMounted(() => {
    getProducts()
    handInquire()
})
</script>
<style lang='scss' scoped>
.demo-form-inline {
    .el-input {
        width: 265px;

    }

    :deep(.el-input__wrapper) {
        border-radius: 20px;
    }
}
</style>